iT邦幫忙

2025 iThome 鐵人賽

DAY 6
3

https://ithelp.ithome.com.tw/upload/images/20250920/20177944t2ppaRvHtM.jpg

https://ithelp.ithome.com.tw/upload/images/20250920/201779443cbvBteDeR.jpg

class Solution{//34 O(LogN) O(1)
public:
    vector<int> searchRange(vector<int>& a, int t){
        int L = lower_bound(a.begin(), a.end(), t) - a.begin();
        if (L == (int)a.size() || a[L] != t) return { -1, -1 };
        int R = upper_bound(a.begin(), a.end(), t) - a.begin() - 1;
        return { L, R };
    }
};

Binary Search 學習中 加油吧 又收到一個機會,但先好好準備再go,決戰十月底maybe

每次比對後把搜尋區間對半縮小
中點(l+r)/2
≥t答案可能在更左,繼續往左找
l<=r;當 r=2 時 l>r,表搜尋區間已空(沒有更左的位置可找),l=3 就是最左邊符合的索引。


上一篇
Sliding Window 9->10 & 還有好聲音可以聽真是不可思議:O
下一篇
Binary Search 3->4 & 補眠日QQ
系列文
轉職仔之Data Science and ai master後的持續精進技術之路10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言